package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.service.ExportService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/export")
@Tag(name = "数据导出模块")
public class ExportController {

    @Autowired
    private ExportService exportService;

    @Autowired
    private UserService userService;

    @Operation(summary = "导出宠物健康记录")
    @GetMapping("/health-records/{petId}")
    public ResponseEntity<String> exportHealthRecords(
            @Parameter(description = "宠物ID") @PathVariable Long petId) {
        try {
            String csvContent = exportService.exportHealthRecords(petId);
            
            if (csvContent.startsWith("导出失败") || csvContent.startsWith("宠物")) {
                // 如果是错误信息，返回错误响应
                return ResponseEntity.badRequest()
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
                        .body(csvContent);
            }

            // 设置响应头，支持下载CSV文件
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("text/csv;charset=UTF-8"));
            headers.setContentDispositionFormData("attachment", 
                "health_records_" + petId + "_" + 
                java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".csv");
            headers.add(HttpHeaders.CONTENT_ENCODING, "UTF-8");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(csvContent);

        } catch (Exception e) {
            log.error("导出宠物健康记录失败", e);
            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
                    .body("导出失败: " + e.getMessage());
        }
    }

    @Operation(summary = "导出订单列表")
    @GetMapping("/orders")
    public ResponseEntity<String> exportOrders(
            @Parameter(description = "用户ID（可选，管理员可查看所有订单）") @RequestParam(required = false) Long userId) {
        try {
            // 如果未指定userId，从当前登录用户获取（普通用户只能导出自己的订单）
            if (userId == null) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                String username = authentication.getName();
                var user = userService.getUserByUsername(username);
                if (user != null) {
                    userId = user.getId();
                }
            }

            String csvContent = exportService.exportOrders(userId);
            
            if (csvContent.startsWith("导出失败")) {
                return ResponseEntity.badRequest()
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
                        .body(csvContent);
            }

            // 设置响应头，支持下载CSV文件
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("text/csv;charset=UTF-8"));
            String fileName = userId != null ? 
                "orders_user_" + userId + "_" : 
                "orders_all_";
            headers.setContentDispositionFormData("attachment", 
                fileName + java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".csv");
            headers.add(HttpHeaders.CONTENT_ENCODING, "UTF-8");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(csvContent);

        } catch (Exception e) {
            log.error("导出订单列表失败", e);
            return ResponseEntity.badRequest()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
                    .body("导出失败: " + e.getMessage());
        }
    }
}

